package uzpay

import (
	"context"
	"fmt"
	"time"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/uzpay/uzpay"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Uzpay{
		SecretKey:  config.SecretKey,
		Url:        config.Url,
		ReturnUrl:  config.ReturnUrl,
		NotifyUrl:  config.NotifyUrl,
		MerchantId: config.MerchantId,
	}
}

type Uzpay struct {
	SecretKey  string
	Url        string
	ReturnUrl  string
	NotifyUrl  string
	MerchantId string
}

// 代付订单创建
func (B *Uzpay) Withdraw(ctx context.Context, req map[string]any) (resp base.WithdrawRes, err error) {
	// 请求第三方接口
	mid := B.MerchantId
	orderid := req["Order"].(map[string]any)["OrderNo"].(string)
	amount := fmt.Sprintf("%.2f", req["Order"].(map[string]any)["OrderAmount"])
	url := B.Url + "/pay/transfer"
	orderDate := time.Now().Format("2006-01-02 15:04:05")
	bankCode := ""
	receiveName := ""
	receiveAccount := ""
	remark := ""
	fmt.Println(req["Order"].(map[string]any)["UserBank"].(map[string]any)["BankCode"].(string))
	if _, exists := req["Order"].(map[string]any)["UserBank"]; exists {
		bankCode = req["Order"].(map[string]any)["UserBank"].(map[string]any)["BankCode"].(string)
		receiveName = req["Order"].(map[string]any)["UserBank"].(map[string]any)["UserName"].(string)
		receiveAccount = req["Order"].(map[string]any)["UserBank"].(map[string]any)["CardNumber"].(string)
		remark = req["Order"].(map[string]any)["UserBank"].(map[string]any)["IfscCode"].(string)
	}
	draw, err := uzpay.Withdraw(url, mid, orderid, amount, orderDate, bankCode, receiveName, receiveAccount, remark, B.NotifyUrl, B.SecretKey)
	if err != nil {
		return resp, err
	} else {
		resp = base.WithdrawRes{
			OrderSn:      req["Order"].(map[string]any)["OrderNo"].(string),
			ThirdOrderSn: draw.TradeNo,
		}
		return resp, err
	}
}
